const mongoose = require('mongoose');

/**
 * 班级数据模型
 */
const classSchema = new mongoose.Schema({
  // 班级名称
  className: {
    type: String,
    required: [true, '班级名称不能为空'],
    trim: true,
    unique: true,
    maxlength: [50, '班级名称不能超过50个字符']
  },
  
  // 年级
  grade: {
    type: String,
    required: [true, '年级不能为空'],
    trim: true,
    maxlength: [20, '年级不能超过20个字符']
  },
  
  // 班主任
  headTeacher: {
    type: String,
    trim: true,
    maxlength: [20, '班主任姓名不能超过20个字符']
  },
  
  // 备注
  description: {
    type: String,
    trim: true,
    maxlength: [200, '备注不能超过200个字符']
  },
  
  // 创建时间
  createdAt: {
    type: Date,
    default: Date.now
  },
  
  // 更新时间
  updatedAt: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true
});

// 添加索引
classSchema.index({ className: 1 });
classSchema.index({ grade: 1 });

/**
 * 获取班级学生数量
 */
classSchema.methods.getStudentCount = async function() {
  const Student = mongoose.model('Student');
  return await Student.countDocuments({ class: this.className });
};

/**
 * 获取班级平均分
 */
classSchema.methods.getAverageScore = async function() {
  const Student = mongoose.model('Student');
  const students = await Student.find({ class: this.className });
  
  if (students.length === 0) return 0;
  
  let totalScore = 0;
  let totalCount = 0;
  
  students.forEach(student => {
    if (student.scores && student.scores.length > 0) {
      const avgScore = student.scores.reduce((sum, item) => sum + item.score, 0) / student.scores.length;
      totalScore += avgScore;
      totalCount++;
    }
  });
  
  return totalCount > 0 ? (totalScore / totalCount).toFixed(2) : 0;
};

/**
 * 删除前检查
 */
classSchema.pre('deleteOne', { document: true, query: false }, async function(next) {
  const Student = mongoose.model('Student');
  const count = await Student.countDocuments({ class: this.className });
  
  if (count > 0) {
    throw new Error(`该班级下还有${count}名学生，无法删除`);
  }
  
  next();
});

const Class = mongoose.model('Class', classSchema);

module.exports = Class;
